<?php
class wap_ctl_delivery extends wap_controller
{
    var $delivery_link    = array();
    var $page_size        = 2;//每页显示数量
    
    function __construct($app)
    {
        parent::__construct($app);
        
        $this->delivery_link['logout']     = app::get('wap')->router()->gen_url(array('ctl'=>'passport','act'=>'logout'), true);
        $this->delivery_link['confirm']    = app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'confirm'), true);
        $this->delivery_link['dispose']    = app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'index'), true);
        $this->delivery_link['ajaxConfirm']   = app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'ajaxConfirm'), true);
        $this->delivery_link['ajaxDly']    = app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'ajaxDly'), true);
        $this->delivery_link['sendMsg']    = app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'sendMsg'), true);
        $this->pagedata['delivery_link']   = $this->delivery_link;
    }
    
    function index()
    {
        //销单校验码开关 关闭状态不显示相关校验码input/button
        if(app::get('o2o')->getConf('o2o.delivery.confirm.code') == "true"){
            $this->pagedata["code_html_show"] = true; 
        }
        $this->display('delivery/sales_delivery.html');
    }

    /**
     * status 0:未处理  1:打回  2:暂停 3:已发货
     */
    function _views_confirm($curr_view)
    {
        $base_filter = array();
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        
        $page              = intval($_GET['page']) ? intval($_GET['page']) : 1;
        $offset            = $this->page_size * ($page - 1);
        $limit             = 2;
        
        $is_super    = kernel::single('desktop_user')->is_super();
        if(!$is_super)
        {
            $branchObj     = kernel::single('o2o_store_branch');
            $branch_ids    = $branchObj->getO2OBranchByUser(true);
            if(empty($branch_ids))
            {
                $this->pagedata['link_url']     = $this->delivery_link['dispose'];
                $this->pagedata['error_msg']    = '操作员没有管辖的仓库';
                echo $this->fetch('auth_error.html');
                exit;
            }
            $base_filter['branch_id']    = $branch_ids;
        }
        
        $sub_menu = array(
                'all' => array('label'=>app::get('base')->_('全部'), 'filter'=>array('status'=>0), 'href'=>$this->delivery_link['confirm']),
                'confirmed' => array('label'=>app::get('base')->_('已确认') ,'filter'=>array('status'=>0, 'confirm'=>1), 'href'=>app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'confirmed'), true)),
                'unconfirmed' => array('label'=>app::get('base')->_('未确认') ,'filter'=>array('status'=>0, 'confirm'=>3), 'href'=>app::get('wap')->router()->gen_url(array('ctl'=>'delivery','act'=>'unconfirmed'), true)),
        );
        
        foreach($sub_menu as $k=>$v)
        {
            if (!IS_NULL($v['filter']))
            {
                $v['filter']    = array_merge($v['filter'], $base_filter);
            }
            
            if($_POST['ship_mobile'])
            {
                $v['filter']['ship_mobile']    = htmlspecialchars(trim($_POST['ship_mobile']));
            }
            if($_POST['ship_name'])
            {
                $v['filter']['ship_name']    = htmlspecialchars(trim($_POST['ship_name']));
            }
            if($_POST['delivery_bn'])
            {
                $v['filter']['delivery_bn']    = htmlspecialchars(trim($_POST['delivery_bn']));
            }
            
            $sub_menu[$k]['filter'] = $v['filter'] ? $v['filter'] : null;
            $sub_menu[$k]['addon'] = $wapDeliveryObj->count($v['filter']);
            
            $sub_menu[$k]['offset'] = $offset;
            $sub_menu[$k]['limit'] = $limit;
            $sub_menu[$k]['orderby'] = 'delivery_id desc';#排序
            
            if($k == $curr_view){
                $sub_menu[$k]['curr_view'] = true;
            }else{
                $sub_menu[$k]['curr_view'] = false;
            }
        }
        
        return $sub_menu;
    }
    
    //调用百度地图接口 显示当前位置到门店的驾车路线
    function showMapByBaidu(){
        $this->title = '当前位置到门店的路线';
        $this->pagedata['ship_addr'] = $_GET["store_addr"];
        $this->pagedata['baidu_map_key'] = app::get('o2o')->getConf('o2o.baidumap.ak');
        $this->display('delivery/baidumap_to_store.html');
    }
    
    /**
     * 确认交付订单列表页
     * 
     * @author: wangbiao@shopex.cn
     */
    function confirm()
    {
        $this->title            = '确认交付订单';
        $this->delivery_type    = 'all';
        
        $sub_menu    = $this->_views_confirm($this->delivery_type);
        $filter      = $sub_menu[$this->delivery_type]['filter'];
        
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $count             = $wapDeliveryObj->count($filter);
        
        $offset            = $sub_menu[$this->delivery_type]['offset'];
        $limit             = $sub_menu[$this->delivery_type]['limit'];
        
        #仓库对应_发货单列表
        $wapDeliveryLib    = kernel::single('wap_delivery');
        
        $dataList          = $wapDeliveryLib->getList($filter, $offset, $limit, $sub_menu[$this->delivery_type]['orderby']);
        
        #分页
        $page_html         = $wapDeliveryLib->multi($count, $this->page_size, $sub_menu[$this->delivery_type]['href']);
        $this->pagedata['page_html']    = $page_html;
        
        $this->pagedata['dataList']    = $dataList;
        $this->pagedata['sub_menu']    = $sub_menu;
        $this->pagedata['link_url']    = $sub_menu[$this->delivery_type]['href'];
        
        //baidu map button show or not
        $baidu_map_show = app::get('o2o')->getConf('o2o.baidumap.show');
        if($baidu_map_show=="true"){
            $this->pagedata["baidu_map_show"] = true;
        }
        
        $this->display('delivery/confirm_delivery.html');
    }
    
    #已确认
    function confirmed()
    {
        $this->title            = '已确认';
        $this->delivery_type    = 'confirmed';
        
        $sub_menu    = $this->_views_confirm($this->delivery_type);
        $filter      = $sub_menu[$this->delivery_type]['filter'];
        
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $count             = $wapDeliveryObj->count($filter);
        
        $offset            = $sub_menu[$this->delivery_type]['offset'];
        $limit             = $sub_menu[$this->delivery_type]['limit'];
        
        #仓库对应_发货单列表
        $wapDeliveryLib    = kernel::single('wap_delivery');
        
        $dataList          = $wapDeliveryLib->getList($filter, $offset, $limit, $sub_menu[$this->delivery_type]['orderby']);
        
        #分页
        $page_html         = $wapDeliveryLib->multi($count, $this->page_size, $sub_menu[$this->delivery_type]['href']);
        $this->pagedata['page_html']    = $page_html;
        
        $this->pagedata['dataList']    = $dataList;
        $this->pagedata['sub_menu']    = $sub_menu;
        $this->pagedata['link_url']    = $sub_menu[$this->delivery_type]['href'];
        
        $this->display('delivery/confirm_delivery.html');
    }
    
    #未确认
    function unconfirmed()
    {
        $this->title            = '未确认';
        $this->delivery_type    = 'unconfirmed';
        
        $sub_menu    = $this->_views_confirm($this->delivery_type);
        $filter      = $sub_menu[$this->delivery_type]['filter'];
        
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $count             = $wapDeliveryObj->count($filter);
        
        $offset            = $sub_menu[$this->delivery_type]['offset'];
        $limit             = $sub_menu[$this->delivery_type]['limit'];
        
        #仓库对应_发货单列表
        $wapDeliveryLib    = kernel::single('wap_delivery');
        
        $dataList          = $wapDeliveryLib->getList($filter, $offset, $limit, $sub_menu[$this->delivery_type]['orderby']);
        
        #分页
        $page_html         = $wapDeliveryLib->multi($count, $this->page_size, $sub_menu[$this->delivery_type]['href']);
        $this->pagedata['page_html']    = $page_html;
        
        $this->pagedata['dataList']    = $dataList;
        $this->pagedata['sub_menu']    = $sub_menu;
        $this->pagedata['link_url']    = $sub_menu[$this->delivery_type]['href'];
        
        $this->display('delivery/confirm_delivery.html');
    }
    
    /**
     * 确认交付订单
     *
     * @param intval  $delivery_id
     * @author: wangbiao@shopex.cn
     */
    function ajaxConfirm()
    {
        $delivery_id    = intval($_POST['delivery_id']);
        $status    = intval($_POST['status']);
        if(empty($delivery_id) || empty($status))
        {
            echo json_encode(array('res'=>'error', 'msg'=>'无效操作'));
            exit;
        }
        
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $fields    = 'delivery_bn, status, print_status, process_status, shop_id, outer_delivery_bn, branch_id, ship_name, sms_group, ship_tel, ship_mobile, confirm, weight, delivery_cost_actual, logi_id';
        $deliveryInfo    = $wapDeliveryObj->dump(array('delivery_id'=>$delivery_id), $fields);
        if(empty($deliveryInfo))
        {
            echo json_encode(array('res'=>'error', 'msg'=>'没有相关发货单'));
            exit;
        }
        elseif($deliveryInfo['status'] > 0 || $deliveryInfo['confirm'] != 3)
        {
            echo json_encode(array('res'=>'error', 'msg'=>'该发货单无法继续操作'));
            exit;
        }

        $dlyProcessLib = kernel::single('wap_delivery_process');
        //组织参数
        $params = array_merge(array('delivery_id'=>$delivery_id), $deliveryInfo);
        $action = $status == 1 ? 'accept' : 'refuse';

        if($action == 'accept'){
            if($dlyProcessLib->accept($params)){
                echo json_encode(array('res'=>'succ', 'msg'=>'门店确认成功'));
                exit;
            }else{
                echo json_encode(array('res'=>'error', 'msg'=>'门店确认失败'));
                exit;
            }

        }elseif($action == 'refuse'){
            if($dlyProcessLib->refuse($params)){
                echo json_encode(array('res'=>'succ', 'msg'=>'门店拒绝成功'));
                exit;
            }else{
                echo json_encode(array('res'=>'error', 'msg'=>'门店拒绝失败'));
                exit;
            }
        }
    }
    
    /**
     * 确认自提收货
     * 
     * @return json
     */
    function ajaxDly()
    {
        $delivery_bn    = $_POST['delivery_bn'];
        $flag           = $_POST['flag'];#是否ajax显示数据
        
        //先检查发货单号 和 管理员对应仓库
        if(empty($delivery_bn)){
            echo json_encode(array('res'=>'error', 'msg'=>'请填写发货单号'));
            exit;
        }
        $filter = array('delivery_bn'=>$delivery_bn);
        
        #管理员对应仓库
        $is_super = kernel::single('desktop_user')->is_super();
        if(!$is_super){
            $branchObj     = kernel::single('o2o_store_branch');
            $branch_ids    = $branchObj->getO2OBranchByUser(true);
            if(empty($branch_ids)){
                echo json_encode(array('res'=>'error', 'msg'=>'操作员没有管辖的仓库'));
                exit;
            }
            $filter['branch_id'] = $branch_ids;
        }
        
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $fields    = 'delivery_id, delivery_bn, status, shop_id, outer_delivery_bn, branch_id, ship_name, ship_tel, ship_mobile, confirm, logi_id, logi_name, order_bn';
        $deliveryInfo    = $wapDeliveryObj->dump($filter, $fields);
        if(empty($deliveryInfo)){
            echo json_encode(array('res'=>'error', 'msg'=>'没有此发货单,请检查'));
            exit;
        }elseif($deliveryInfo['status'] == 3){
            echo json_encode(array('res'=>'error', 'msg'=>'该发货单已发货,不能进行操作'));
            exit;
        }elseif($deliveryInfo['confirm'] != 1){
            $confirm_error_msg = "该发货单还未确认,不能进行操作";
            if($deliveryInfo['confirm'] == 2){
                $confirm_error_msg = "该发货单已被拒绝,不能进行操作";
            }
            echo json_encode(array('res'=>'error', 'msg'=>$confirm_error_msg));
            exit;
        }
        
        //开启销单校验码需检查校验码
        if(app::get('o2o')->getConf('o2o.delivery.confirm.code') == "true"){
            $code = $_POST['check_code'];
            if(empty($code)){
                echo json_encode(array('res'=>'error', 'msg'=>'请填写校验码'));
                exit;
            }
            $wapDeliveryCodeObj = app::get('wap')->model('delivery_code');
            $rs_code = $wapDeliveryCodeObj->dump(array('delivery_bn'=>$delivery_bn), '*');
            if($rs_code['code'] != $code){
                echo json_encode(array('res'=>'error', 'msg'=>'校验码填写错误'));
                exit;
            }elseif($rs_code['status'] == 1){
                echo json_encode(array('res'=>'error', 'msg'=>'校验码已使用'));
                exit;
            }
        }
        
        #获取发货仓库对应的门店店铺信息
        $wapDeliveryLib    = kernel::single('wap_delivery');
        $dlyProcessLib = kernel::single('wap_delivery_process');
        $branchShopInfo    = $wapDeliveryLib->getBranchShopInfo($deliveryInfo['branch_id']);
        
        #获取订单信息
//         $deliveryInfo['order_info']    = $wapDeliveryLib->getDeliverBnByOrderInfo($deliveryInfo['outer_delivery_bn']);
        //在wap_delivery表中新加 order_bn,total_amount字段  是在生成新的o2o发货单是直接从订单表中带过来的  @wangjianjun
        $deliveryInfo['order_info'] = array(
                "order_bn" => $deliveryInfo["order_bn"]
        );
        
        $deliveryInfo['order_number']  = 1;
        
        #合并数据
        $result    = array_merge($deliveryInfo, $branchShopInfo);
        unset($data['wms_id'], $data['store_id'], $data['area'], $data['confirm'], $data['branch_id']);
        
        #输入校验码_ajax显示相关数据
        if($flag == 'true')
        {
            echo json_encode(array('res'=>'ajaxload', 'msg'=>'', 'result'=>$result));
            exit;
        }
        
        #执行具体的发货处理事务
        $res    = $dlyProcessLib->consignDelivery($deliveryInfo);
        if($res){
            $msg = $deliveryInfo["logi_name"]."成功";
            echo json_encode(array('res'=>'succ', 'msg'=>$msg, 'result'=>$result));
            exit;
        }else {
            $msg = $deliveryInfo["logi_name"]."失败";
            echo json_encode(array('res'=>'fail', 'msg'=>$msg, 'result'=>$result));
            exit;
        }
    }

    /**
     * 重发提货校验码
     * 
     * @return json
     */
    function sendMsg(){
        
        //开启销单校验码才能重新生成校验码
        if(app::get('o2o')->getConf('o2o.delivery.confirm.code') == "false"){
            echo json_encode(array('res'=>'error', 'msg'=>'开启销单校验码才能重新生成校验码'));
            exit;
        }
        
        $delivery_bn    = $_POST['delivery_bn'];

        if(empty($delivery_bn))
        {
            echo json_encode(array('res'=>'error', 'msg'=>'无效操作'));
            exit;
        }

        $wapDeliveryObj    = app::get('wap')->model('delivery');
        $fields    = 'delivery_id, delivery_bn, status, shop_id, outer_delivery_bn, branch_id, ship_name, ship_tel, ship_mobile, confirm, logi_id';
        $deliveryInfo    = $wapDeliveryObj->dump(array('delivery_bn'=>$delivery_bn), $fields);
        if(empty($deliveryInfo))
        {
            echo json_encode(array('res'=>'error', 'msg'=>'没有相关发货单'));
            exit;
        }
        elseif($deliveryInfo['status'] > 0 || $deliveryInfo['confirm'] != 1)
        {
            echo json_encode(array('res'=>'error', 'msg'=>'该发货单无法继续操作'));
            exit;
        }

        $dlyProcessLib = kernel::single('wap_delivery_process');
        $res    = $dlyProcessLib->reSendMsg($deliveryInfo);
        if($res)
        {
            echo json_encode(array('res'=>'succ', 'msg'=>'提货校验码发送成功', 'result'=>$result));
            exit;
        }
        else 
        {
            echo json_encode(array('res'=>'fail', 'msg'=>'提货校验码发送失败', 'result'=>$result));
            exit;
        }
    }
}
